package com.doctorliang.cheng.shopping.home.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.doctorliang.cheng.shopping.R;
import com.doctorliang.cheng.shopping.app.GoodsInfoActivity;
import com.doctorliang.cheng.shopping.home.bean.GoodsBean;
import com.doctorliang.cheng.shopping.home.bean.ResultBeanData;
import com.doctorliang.cheng.shopping.utils.Constants;
import com.doctorliang.cheng.shopping.utils.ToastUtil;
import com.gigamole.infinitecycleviewpager.HorizontalInfiniteCycleViewPager;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerClickListener;
import com.youth.banner.listener.OnLoadImageListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by CHENG on 2017/9/27.
 */

public class HomeFragmentAdapter extends RecyclerView.Adapter {

    /**
     * 五种类型
     */
    /**
     * 横幅广告
     */
    public static final int BANNER = 0;
    /**
     * 频道
     */
    public static final int CHANNEL = 1;

    /**
     * 活动
     */
    public static final int ACT = 2;

    /**
     * 秒杀
     */
    public static final int SECKILL = 3;
    /**
     * 推荐
     */
    public static final int RECOMMEND = 4;
    /**
     * 热卖
     */
    public static final int HOT = 5;
    public static final String GOODS_BEAN = "goodsbean";
    private final Context mcontext;
    private final ResultBeanData.ResultBean results;
    /**
     * 初始化布局
     */
    private final LayoutInflater layoutInflater;

    /**
     * 当前类型
     */
    public int currentType = BANNER;
    /**
     * 倒计时
     */
    private long dt;
    /**
     * 用来控制时间，保证下次不会重置倒计时
     */
    private boolean isfirst = true;

    /**
     * 秒杀点击接口实例
     */

    public HomeFragmentAdapter(Context mcontext, ResultBeanData.ResultBean results) {
        this.mcontext = mcontext;
        this.results = results;
        //初始化布局
        layoutInflater = LayoutInflater.from(mcontext);
    }


    /**
     * 相当于getView中的viewHoldre部分
     *
     * @param parent
     * @param viewType
     * @return
     */
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == BANNER) {
            return new BannerViewHolder(layoutInflater.inflate(R.layout.banner_viewpager, null), mcontext);
        }
        if (viewType == CHANNEL) {
            return new ChannelViewHolder(layoutInflater.inflate(R.layout.channel_item, null), mcontext);
        }
        if (viewType == ACT) {
            return new ActViewHolder(layoutInflater.inflate(R.layout.act_item, null), mcontext);
        }
        if (viewType == SECKILL) {
            return new SeckillViewHolder(layoutInflater.inflate(R.layout.seckill_item, null), mcontext);
        }if(viewType == RECOMMEND){
            return new RecommendViewHolder(layoutInflater.inflate(R.layout.recommend_item1, null), mcontext);
        }if(viewType == HOT){
            return new HotViewHolder(layoutInflater.inflate(R.layout.hot_item1, null), mcontext);
        }

        return null;
    }

    /**
     * 绑定数据
     *
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == BANNER) {
            BannerViewHolder bannerViewHolder = (BannerViewHolder) holder;
            bannerViewHolder.setData(results.getBanner_info());
        }
        if (getItemViewType(position) == CHANNEL) {
            ChannelViewHolder channelViewHolder = (ChannelViewHolder) holder;
            channelViewHolder.setData(results.getChannel_info());
        }
        if (getItemViewType(position) == ACT) {
            ActViewHolder actViewHolder = (ActViewHolder) holder;
            actViewHolder.setData(results.getAct_info());
        }
        if (getItemViewType(position) == SECKILL) {
            SeckillViewHolder seckillViewHolder = (SeckillViewHolder) holder;
            seckillViewHolder.setData(results.getSeckill_info());
        }if (getItemViewType(position) == RECOMMEND) {
            RecommendViewHolder recommendViewHolder = (RecommendViewHolder) holder;
            recommendViewHolder.setData(results.getRecommend_info());
        }if (getItemViewType(position) == HOT) {
            HotViewHolder hotViewHolder = (HotViewHolder) holder;
            hotViewHolder.setData(results.getHot_info());
        }
    }

    /**
     * 得到每一种类型
     *
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {
        switch (position) {
            case BANNER:
                currentType = BANNER;
                break;
            case CHANNEL:
                currentType = CHANNEL;
                break;
            case ACT:
                currentType = ACT;
                break;
            case SECKILL:
                currentType = SECKILL;
                break;
            case RECOMMEND:
                currentType = RECOMMEND;
                break;
            case HOT:
                currentType = HOT;
                break;
        }
        return currentType;
    }

    /**
     * 返回recycle的类型总数
     *
     * @return
     */
    @Override
    public int getItemCount() {
        return 6;
    }

    private class BannerViewHolder extends RecyclerView.ViewHolder {
        private final Context mcontext;
        private Banner banner;

        public BannerViewHolder(View itemView, Context mcontext) {
            super(itemView);
            this.mcontext = mcontext;
            banner = itemView.findViewById(R.id.banner);
        }

        /**
         * 设置bannerviewholder的数据
         *
         * @param banner_info
         */
        public void setData(List<ResultBeanData.ResultBean.BannerInfoBean> banner_info) {
            List<String> imagesUrl = new ArrayList<>();
            for (int i = 0; i < results.getBanner_info().size(); i++) {
                String imageurl = banner_info.get(i).getImage();
                Log.e("img",imageurl);
                imagesUrl.add(imageurl);
            }
            //手风琴效果
            banner.setBannerAnimation(Transformer.Accordion);
            //设置位置效果（下面的点）
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            banner.setImages(imagesUrl, new OnLoadImageListener() {
                @Override
                public void OnLoadImage(ImageView view, Object url) {
                    Log.e("img",Constants.BASE_URl_IMAGE + url);
                    Glide.with(mcontext).load(Constants.BASE_URl_IMAGE + url).into(view);
                }
            });
            //设置点击事件
            banner.setOnBannerClickListener(new OnBannerClickListener() {
                @Override
                public void OnBannerClick(int position) {
                    ToastUtil.showShort(mcontext,"position" + position);

//                    mcontext.startActivity(new Intent(mcontext, GoodsInfoActivity.class));

                }
            });

        }
    }

    class ChannelViewHolder extends RecyclerView.ViewHolder {
        public final Context mcontext;
        public GridView gridView;

        public ChannelViewHolder(View view, Context mcontext) {
            super(view);
            this.mcontext = mcontext;
            gridView = view.findViewById(R.id.gv_channel);
        }

        /**
         * 设置channel的数据
         *
         * @param channel_info
         */
        public void setData(List<ResultBeanData.ResultBean.ChannelInfoBean> channel_info) {
            gridView.setAdapter(new ChannelAdapter(mcontext, channel_info));
            //点击事件
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                    Toast.makeText(mcontext, "position" + i, Toast.LENGTH_SHORT).show();

                    ToastUtil.showShort(mcontext,"position" + i);

//                    mcontext.startActivity(new Intent(mcontext, GoodsInfoActivity.class));

                }
            });

        }
    }

    /**
     * 活动的viewholder
     */
    public class ActViewHolder extends RecyclerView.ViewHolder {
        public final Context mcontext;
        public HorizontalInfiniteCycleViewPager viewPager;

        public ActViewHolder(View view, Context mcontext) {
            super(view);
            this.mcontext = mcontext;
            viewPager = view.findViewById(R.id.act_viewpager);
        }
        /**
         * 设置活动的数据
         */
        public void setData(final List<ResultBeanData.ResultBean.ActInfoBean> act_info) {
            viewPager.setPageMargin(5);
            viewPager.setScrollDuration(500);
//
            viewPager.setMediumScaled(true);
            viewPager.setMaxPageScale(0.8F);
            viewPager.setMinPageScale(0.5F);
            viewPager.setCenterPageScaleOffset(30.0F);
            viewPager.setMinPageScaleOffset(5.0F);
//            viewPager.setOnInfiniteCyclePageTransformListener(...);
            viewPager.setAdapter(new PagerAdapter() {
                @Override
                public int getCount() {
                    return act_info.size();
                }

                @Override
                public boolean isViewFromObject(View view, Object object) {
                    return view == object;
                }

                @Override
                public Object instantiateItem(ViewGroup container, final int position) {
                    ImageView imageView = new ImageView(mcontext);
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    Glide.with(mcontext).load(Constants.BASE_URl_IMAGE + act_info.get(position).getIcon_url()).into(imageView);
                    container.addView(imageView);
                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
//                            Toast.makeText(mcontext, "position" + position, Toast.LENGTH_SHORT).show();
                            ToastUtil.showShort(mcontext,"position" + position);
//                            mcontext.startActivity(new Intent(mcontext, GoodsInfoActivity.class));

                        }
                    });

                    return imageView;
                }

                @Override
                public void destroyItem(ViewGroup container, int position, Object object) {
                    container.removeView((View) object);
                }
            });
        }
    }

    private class SeckillViewHolder extends RecyclerView.ViewHolder {
        private final Context mcontext;
        private TextView tvTime;
        private TextView tvMore;
        private RecyclerView recyclerView;

        public SeckillViewHolder(View itemView, Context mcontext) {
            super(itemView);
            tvTime = (TextView) itemView.findViewById(R.id.tv_time_seckill);
            tvMore = (TextView) itemView.findViewById(R.id.tv_more_seckill);
            recyclerView = (RecyclerView) itemView.findViewById(R.id.rv_seckill);
            this.mcontext = mcontext;
        }
        private Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        dt = dt - 1000;
                        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                        String mdt = format.format(new Date(dt));
                        tvTime.setText(mdt);
                        //先移除，再发送
                        handler.removeCallbacksAndMessages(null);
                        handler.sendEmptyMessageDelayed(1,1000);
                        if (dt==0) {
                            handler.removeMessages(1);
                        }
                        break;
                }

            }
        };
        /**
         * 设置秒杀的数据
         *
         * @param seckill_info
         */
        public void setData(ResultBeanData.ResultBean.SeckillInfoBean seckill_info) {
            //得到数据，设置文本和recycleview的内容
            SeckillRecycleViewAdapter adapter = new SeckillRecycleViewAdapter(mcontext, seckill_info.getList());
            recyclerView.setAdapter(adapter);
            //设置布局管理器
            recyclerView.setLayoutManager(new LinearLayoutManager(mcontext, LinearLayoutManager.HORIZONTAL, false));
            //设置秒杀的点击事件,这里自己写接口回调
            adapter.setOnSeckillRecyclerView(new SeckillRecycleViewAdapter.OnSeckillRecyclerView() {
                @Override
                public void onItemClick(int position) {
//                    Toast.makeText(mcontext, "position==" + position, Toast.LENGTH_SHORT).show();
                    ToastUtil.showShort(mcontext,"position" + position);

//                    mcontext.startActivity(new Intent(mcontext, GoodsInfoActivity.class));

                }
            });
            if (isfirst) {
                dt = Integer.valueOf(seckill_info.getEnd_time()) - Integer.valueOf(seckill_info.getStart_time());
            }
            handler.sendEmptyMessageDelayed(1,1000);

        }

    }


    /**
     * 推荐内容的viewholder
     */
    private class RecommendViewHolder extends RecyclerView.ViewHolder {
        private final Context mcontext;
        private TextView tv_more_recommend;
        private GridView gv_recommend;
        public RecommendViewHolder(View view, Context mcontext) {
            super(view);
            tv_more_recommend = (TextView) itemView.findViewById(R.id.tv_more_recommend);
            gv_recommend = (GridView) itemView.findViewById(R.id.gv_recommend);
            this.mcontext = mcontext;
        }

        public void setData(final List<ResultBeanData.ResultBean.RecommendInfoBean> recommend_info) {
            //有数据 设置适配器
            RecommendAdapter adapter = new RecommendAdapter(mcontext, recommend_info);
            gv_recommend.setAdapter(adapter);
            //监听位置
            gv_recommend.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    ResultBeanData.ResultBean.RecommendInfoBean recommendInfoBean = recommend_info.get(i);
                    GoodsBean goodsBean = new GoodsBean();
                    goodsBean.setCover_price(recommendInfoBean.getCover_price());
                    goodsBean.setFigure(recommendInfoBean.getFigure());
                    goodsBean.setName(recommendInfoBean.getName());
                    goodsBean.setProduct_id(recommendInfoBean.getProduct_id());
                    startGoodsInfoActivity(goodsBean);
                }
            });

        }
    }

    private void startGoodsInfoActivity(GoodsBean goodsBean) {
        Intent intent = new Intent(mcontext, GoodsInfoActivity.class);
        intent.putExtra(GOODS_BEAN,goodsBean);
        mcontext.startActivity(intent);
    }

    /**
     * 热卖viewholder
     */
    private class HotViewHolder extends RecyclerView.ViewHolder {
        private final Context mcontext;
        private TextView tv_more_hot;
        private GridView gv_hot;
        public HotViewHolder(View view, Context mcontext) {
            super(view);
            tv_more_hot = (TextView) view.findViewById(R.id.tv_more_hot);
            gv_hot = (GridView) view.findViewById(R.id.gv_hot);
            this.mcontext = mcontext;
        }

        /**
         * 设置热卖的数据
         * @param hot_info
         */
        public void setData(final List<ResultBeanData.ResultBean.HotInfoBean> hot_info) {
            //有数据 填充适配器
            gv_hot.setAdapter(new HotAdapter(mcontext,hot_info));
            //监听位置,点击事件
            gv_hot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    ResultBeanData.ResultBean.HotInfoBean hotInfoBean = hot_info.get(i);
                    GoodsBean goodsBean = new GoodsBean();
                    goodsBean.setCover_price(hotInfoBean.getCover_price());
                    goodsBean.setFigure(hotInfoBean.getFigure());
                    goodsBean.setName(hotInfoBean.getName());
                    goodsBean.setProduct_id(hotInfoBean.getProduct_id());
                    startGoodsInfoActivity(goodsBean);
                }
            });

        }
    }
}
